﻿using System.Collections.Generic;
using System.Linq;

namespace Awesome.Extensions.Nullable
{
    public static class NullableEx
    {
        /// <summary>
        /// Check if nulable has value and value equals to target
        /// </summary>
        public static bool ValueEquals<T>(this T? nullable, T target)
            where T : struct
        {
            return (nullable.HasValue && nullable.Value.Equals(target));
        }

        /// <summary>
        /// Returns value of Nullable or default
        /// </summary>
        public static T DefaultValue<T>(this T? nullable, T @default)
            where T : struct
        {
            return nullable.HasValue ? nullable.Value : @default;
        }


        /// <summary>
        /// Converts value to Nullable
        /// </summary>
        public static T? AsNullable<T>(this T value)
            where T : struct
        {
            return value;
        }


        /// <summary>
        /// Returns onlu elements with value 
        /// </summary>
        public static IEnumerable<T> OnlyWithValue<T>(this IEnumerable<T?> source)
            where T : struct
        {
            return source.Where(element => element.HasValue).SelectValues();
        }


        /// <summary>
        /// Select values from sequence of Nullables
        /// </summary>
        public static IEnumerable<T> SelectValues<T>(this IEnumerable<T?> source)
            where T : struct
        {
            return source.Select(v => v.Value);
        }

        public static IEnumerable<T> SelectValueOrDefault<T>(this IEnumerable<T?> source, T @default)
            where T:struct
        {
            return source.Select(v => v.HasValue ? v.Value : @default);
        }
    }
}